# -*- coding: utf-8 -*- 
import requests
import json
import uuid
import os
import struct
import subprocess
import time
import sys,signal
import threading
import logging

import commands
 
import socket
import platform

from threading import Thread
import socketNet
import models
import moniterCP
g_host = '127.0.0.1'
# g_host = 'cgdemo.kjdashi.com'
# g_host = 'gmcg.kjdashi.com'
g_port = 8000

g_face_host = 'cgdemo.kjdashi.com'
#g_face_host = 'cgio.visualdeep.com'
g_face_port =8002 

#g_webHttpUrl = 'http://192.168.190.209:9999/CityInspectors/'
g_webHttpUrl = 'http://cg.visualdeep.com:18200/CityInspectors/'

g_checkImageUrl='http://127.0.0.1:1234/?img='

g_homePath = '/home/nvidia/face/'

uploadUrl = ''


g_subPushPid = -1

g_rtspUrl = ''

g_face = 'face'

g_push ='push'

g_runfacemap = {}

g_pushRTMPMap = {}

padSid = ''

baseUrl = 'http://192.168.1.102:8081/face'

# g_localTypeList=['ZYR','SSJC']

g_localTypeList=['CP','RL']
# g_localTypeList=['CP']

sendImageTimer = None


#获取mac地址
def get_mac_address():
	node = uuid.getnode()
	mac = uuid.UUID(int = node).hex[-12:]
	return mac

# macId = get_mac_address()

macId = 'HS001'


def pkillNames(nameList):

	# rip = name
	# me = commands.getoutput("whoami")
	# p = commands.getoutput("ps -u %s -o cmd -o pid |grep %s" % (me,name) )
	msg =''

	for name in nameList:
		msg = msg+'-e '+name+' '

	msgline = "ps -o cmd -o pid |grep "+msg
	print msgline
	p = commands.getoutput(msgline)

	ids = p.split("\n")

	# print u'发起全部停止操作:'+name
	for id in ids:
		kpid =id.split(' ')
		print kpid 
		kpidStr = unicode(''.join(kpid[-1:]))
		if kpidStr.isdecimal():
			print "kill %d" % int(kpidStr)
			os.system("kill %d" % int(kpidStr))

def pkillAll(nameList):

	for name in nameList:
		logging.info('kill ' + name)
		os.system('pkill ' + name)


def getip():
	try:
		s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		s.connect(('8.8.8.8', 0))
		ip = s.getsockname()[0]
	except:
		ip = "x.x.x.x"
	finally:
		s.close()
		return ip
 
def getIpforSys():
	sysstr = platform.system()
	if sysstr == "Windows":
		ip_address = socket.gethostbyname(socket.gethostname())
		return ip_address
	elif sysstr == "Linux":
		ip_address = getip()
		return ip_address
	elif sysstr == "Darwin":
		ip_address = socket.gethostbyname(socket.gethostname())
		return ip_address
	else:
		return "0.0.0.0"



def cddPushRtmp(res):
	url = res['url']
	cddid = res['cddid']
	sourcesid = res['sourcesid']


	idflag = g_push+"_"+cddid

	logging.info('推流开始:'+str(url))


	if res.has_key('mp4'):
		msgline = 'ffmpeg -re -i ' + str(res['mp4']) + ' -c copy -f flv ' + url
	elif res.has_key('rtsp'):
		#msgline = './push.bin push'+' '+res['rtsp'] +' '+url +' '+idflag
		msgline = 'ffmpeg -f lavfi -i anullsrc -rtsp_transport tcp -i '+res['rtsp']+' -vcodec libx264 -t 2:00:00 -pix_fmt + -c:v copy -c:a aac -strict experimental -f flv '+url
	# msgline = './push.bin push'+' '+rtsp +' '+url +' '+idflag
	# msgline = 'ffmpeg -re -i ' + 'localFile.mp4 -c copy -f flv rtmp://server/live/streamName'

	logging.info('推流执行命令:'+str(msgline))

	push_thread = threading.Thread(target=pushRTMPCommendexec, name="pushRTMPThread",args = (msgline,cddid,))
	# getImage_thread.setDaemon(True)
	push_thread.start()


def cddStopRtmp(res):
	cddid = res['cddid']


	# idflag = g_push+"_"+cddid

	# pkillNames([idflag])
	# pkillNames(['ffmpeg',cddid])
	if g_pushRTMPMap.has_key(cddid):
		
		# sendDict={}
		# sendDict['bigface'] = 'bigface'
		# sendDict['cid'] = message['cid']
		# sendDict['smallface'] = 'smallface'
		# global g_socketio
		# g_socketio.emit('onfaces', sendDict)
		try:
			proc = g_pushRTMPMap[cddid]
			proc.terminate()
			proc.wait()
			os.killpg(proc.pid, signal.SIGTERM)
		except Exception as e:
			print e


	# global g_subPushPid
	# if g_subPushPid>-1:

	# 	logging.info('推流停止:'+str(g_subPushPid))
	# 	try:
	# 		# os.system('kill '+ str(g_subpid))
	# 		os.killpg(os.getpgid(g_subPushPid),signal.SIGTERM)
	# 	except Exception, e:
	# 		logging.error('kill error :'+str(g_subPushPid))
	# 	finally:

	# 		g_subPushPid = -1

def pushRTMPCommendexec(func,cddid):
	res = subprocess.Popen(func, stdin=subprocess.PIPE, stdout=subprocess.PIPE,shell = True, preexec_fn = os.setpgrp)
	global g_subPushPid
	g_subPushPid =res.pid
	global g_pushRTMPMap
	g_pushRTMPMap[cddid] = res

	logging.info('推流执行进程 pid:'+str(res.pid))




def startFace(message):

	# pkillNames(['main.bin'])

	msgline = './main.bin ' + str(message['deviceRtspUrl'])+ ' 0.35 0 0'
	print (msgline)

	t = threading.Thread(target=startCommendexec, name="tttname",args = (msgline,str(message['deviceNumber']),))
	t.setDaemon(True)
	t.start()

	# time.sleep(40)


def teststartface():
	msgline = './main.bin test.mp4 0.35 0 0 '
	t = threading.Thread(target=startCommendexec, name="tttname",args = (msgline,'A1010',' ','t123',))
	t.setDaemon(True)
	t.start()


def stopFace(message):
	if g_runfacemap.has_key(message):
		try:
			proc = g_runfacemap[message]
			proc.terminate()
			proc.wait()
			os.killpg(proc.pid, signal.SIGTERM)
		except Exception as e:
			print e

def startCommendexec(msgline,cddid):
	res = subprocess.Popen(msgline, stdin=subprocess.PIPE, stdout=subprocess.PIPE,shell = True, preexec_fn = os.setpgrp)
	indexflag=True
	sendDict ={}
	checkFaceList = []
	sendFaceFlag = 0

	global g_runfacemap
	g_runfacemap[cddid] = res

	while True:
		
		result = res.stdout.readline()
		print result
		if result=='':
			return
		
	
		if result.find('===smallface:')>-1:
			if not sendDict.has_key('frImageurl'):
				sendDict['frImageurl'] = []
			smalllist = result.split(':')
			smallImagep = smalllist[1].split(',')
			imageUrl = smallImagep[0].strip()
			sendDict['frImageurl'].append(imageUrl[1:len(imageUrl)])

			checkFaceList.append(smallImagep[0].strip())#添加人脸路径

			
		if result.find('===bigface:')>-1:
			biglist = result.split(':')
			bigImage = biglist[1].strip()
			sendDict['frBigImageurl'] = bigImage[1:len(bigImage)]


			if sendDict.has_key('frBigImageurl'):
				sendDict['deviceNumber'] = cddid
				# global g_socketio
				# g_socketio.emit('onfaces', sendDict)

				socketNet.sendPro('W11',sendDict)
				gpsData = moniterCP.getGPSData()
				print gpsData
				for imgurl in sendDict['frImageurl']:
					models.FaceRecordThread().insert(imgurl,sendDict['frBigImageurl'],cddid,gpsData)
				
				sendDict = {}#清除已经发送的数据

		
		if result.find('Detect')>-1:
			sendFaceFlag = sendFaceFlag+1

			if sendFaceFlag%2==0:
				if len(checkFaceList)>0:
					print '发送检测人脸请求'
					#发送检测人脸请求
					# imageList =[]
					faceSendData = {}
					faceSendData['checkId'] = macId
					faceSendData['cid'] = cddid
					faceSendData['images'] = []
					# logging.info('=========')
					# logging.info(faceSendData)
					# logging.info('---------')
					for rurl in checkFaceList:

						sendImage = {}
						sendImage['name'] = rurl
						with open(rurl, 'rb') as rf:
							tmpr = rf.read()
							bt = unpack_list(tmpr)
							sendImage['content'] = bt
						faceSendData['images'].append(sendImage)

					socketNet.sendFacePro('H11',faceSendData)
					checkFaceList = []

		# wx.CallAfter(pub.sendMessage, "updateLogText", msg=result)
		
		time.sleep(0.1)
	if sendDict.has_key('bigFaceImagePath'):
		sendDict['cddid'] = cddid
		global g_socketio
		g_socketio.emit('onfaces', sendDict)
		sendDict = {}

def updataImage():


	try:
		# logging.info('开始发送图片:'+str(upUrl))
		httpRes = requests.post(upUrl['url'],json=sendDict)
		# logging.info('发送图片请求后返回值:'+str(httpRes.text))
	except Exception, e:
		logging.info(e)
		logging.info('发送图片出错')

#---------------------------------------------------------
#向曲亮转发学习黑名单数据
def downloadFace(requestMap):
	# checkId = requestMap['checkId']
	# point = requestMap['points']
	# imageList = requestMap['imageList']
	socketNet.sendFacePro('H10',requestMap)

#向服务器返回曲亮检测好的数据



def on_trade_response(): 
	print(data) 
	
#字符转为对应ASCII码
def unpack_list(str):
	return list(struct.unpack('%dB'%len(str), str))

#整形元祖转化为字符串
def pack_bin(arr):
	return struct.pack('%dB'%len(arr), *arr)



if __name__ == "__main__":

	os.chdir(g_homePath)
	
	logging.basicConfig(level=logging.INFO, format='%(asctime)s %(filename)s(%(funcName)s)[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S')
	if not(os.path.exists('./imageList')):
		os.mkdir('./imageList')
	if not(os.path.exists('./regionsList')):
		os.mkdir('./regionsList')
	#判断文件夹是否存在，没存在则创建

	if not(os.path.exists('./resImageList')):
		os.mkdir('./resImageList')

	if not(os.path.exists('./log')):
		os.mkdir('./log')

	threadStartFace = threading.Thread(target=threadStartFace, name="threadStartFace",args = ('',))
	threadStartFace.start()
	print '========send success=============='


